package com.dule.Medic.service_hibernate;

import org.hibernate.Criteria; 
import org.hibernate.Session;  
import org.hibernate.criterion.Restrictions;
import java.io.Serializable;
import java.util.List;

import com.dule.Medic.beans.DoctorBean;
import com.dule.Medic.beans.MedEntryBean;
import com.dule.Medic.beans.PatientBean;
import com.dule.Medic.model.Doctor;
import com.dule.Medic.model.MedEntry;
import com.dule.Medic.model.Patient;
import com.dule.Medic.service.DoctorService;

public class DoctorHibernateService implements DoctorService {

	private final Session session;
	
	public DoctorHibernateService(Session session) 
	{
		this.session = session; 
	}
	
	public Long save(Doctor doctor) {
		Long id = (Long) session.save(doctor);
		return  id;  
	}
	
	public boolean update(Doctor doctor) 
	{
		session.merge(doctor);
		return true;
	}

	public Doctor get(Long id) {
		return (Doctor) session.get(DoctorBean.class, id); 
	}

	public Doctor retrive(Doctor doctor) 
	{
		Criteria crit = session.createCriteria(DoctorBean.class).add(Restrictions.eq("userName", doctor.getUserName())).add(Restrictions.eq("password", doctor.getPassword()));    
		return (Doctor) crit.uniqueResult();  
	}
	
	public Doctor retrive(Long id) 
	{
		return (Doctor) session.get(DoctorBean.class, id); 
	}
	
	public boolean changeDoctorInfo(Doctor doctor)
	{  
		session.update(doctor);
		return true;  
	} 
	
	public boolean deleteDoctor(Doctor doctor)
	{
		doctor.getMedEntries().size();	
		for (int i = 0 ;i<doctor.getMedEntries().size();i++)
		{	
				MedEntry me=doctor.getMedEntries().get(i);
				doctor.RemoveMedEntry(me);
				session.merge(doctor);
				Patient pt=(Patient) session.get(PatientBean.class, me.getPatient().getId()) ;
				pt.RemoveMedEntry(pt.getMedEntryById(me.getId()));
				session.merge(pt);
				session.delete((MedEntry)session.load(MedEntryBean.class, me.getId()));
				i--;
		}
		session.delete(retrive(doctor));
		return true;
	}

	public Doctor findDoctor(Serializable id)
	{
		return (Doctor) session.load(DoctorBean.class, id);
	}

	@SuppressWarnings("unchecked")
	public List<Doctor> retrieveAll() 
	{
		List<Doctor> doctors=session.createCriteria(DoctorBean.class).list(); 
		return doctors;
	}
	
}
